<script setup lang="ts">
import { useI18n } from "vue-i18n";
import Motion from "./utils/motion";
import { useRoute, useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  onBeforeUnmount,
  onBeforeMount
} from "vue";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import globalization from "@/assets/svg/globalization.svg?component";
import User from "@/assets/svg/user.svg?component";
import Lock from "@/assets/svg/lock.svg?component";
import Check from "@iconify-icons/ep/check";

defineOptions({
  name: "Login"
});
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { t } = useI18n();
const { dataTheme, overallStyle, dataThemeChange } = useDataThemeChange();
dataThemeChange(overallStyle.value);
const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { locale, translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  username: "",
  password: ""
});

const onLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      useUserStoreHook()
        .loginByUsername({
          account: ruleForm.username.trim(),
          password: ruleForm.password.trim()
        })
        .then(res => {
          if (res.code === 200) {
            // 获取后端路由
            return initRouter().then(() => {
              router.push(getTopMenu(true).path).then(() => {
                message(t("login.pureLoginSuccess"), { type: "success" });
              });
            });
          } else {
            message(t("login.pureLoginFail"), { type: "error" });
          }
        })
        .finally(() => (loading.value = false));
    }
  });
};

const onForget = () => {
  message("请联系管理员修改或重置密码！", {
    type: "warning"
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (["Enter", "NumpadEnter"].includes(code)) {
    onLogin(ruleFormRef.value);
  }
}

onBeforeMount(() => {
  const query = route.query;
  if (query?.reset === "1") {
    const urlWithoutParams = window.location.origin + window.location.pathname;

    // 替换当前URL并重新加载页面
    window.location.replace(urlWithoutParams);
  }
});

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="login-container z-10">
      <div class="login-box">
        <div class="flex-c absolute right-5 top-3 z-[11]">
          <!-- 主题 -->
          <!--      <el-switch-->
          <!--        v-model="dataTheme"-->
          <!--        inline-prompt-->
          <!--        :active-icon="dayIcon"-->
          <!--        :inactive-icon="darkIcon"-->
          <!--        @change="dataThemeChange"-->
          <!--      />-->
          <!-- 国际化 -->
          <el-dropdown trigger="click">
            <globalization
              class="hover:text-primary hover:!bg-[transparent] w-[26px] h-[26px] ml-1.5 cursor-pointer outline-none duration-300"
            />
            <template #dropdown>
              <el-dropdown-menu class="translation">
                <el-dropdown-item
                  :style="getDropdownItemStyle(locale, 'zh')"
                  :class="[
                    'dark:!text-white',
                    getDropdownItemClass(locale, 'zh')
                  ]"
                  @click="translationCh"
                >
                  <IconifyIconOffline
                    v-show="locale === 'zh'"
                    class="check-zh"
                    :icon="Check"
                  />
                  简体中文
                </el-dropdown-item>
                <el-dropdown-item
                  :style="getDropdownItemStyle(locale, 'en')"
                  :class="[
                    'dark:!text-white',
                    getDropdownItemClass(locale, 'en')
                  ]"
                  @click="translationEn"
                >
                  <span v-show="locale === 'en'" class="check-en">
                    <IconifyIconOffline :icon="Check" />
                  </span>
                  English
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="login-form">
          <Motion>
            <div class="login-title">{{ t("login.login_title") }}</div>
          </Motion>
          <Motion>
            <div class="login-sub-title">
              {{ t("login.login_system_title") }}
            </div>
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
            class="login-form_wrap"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: transformI18n($t('login.pureUsernameReg')),
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  v-model="ruleForm.username"
                  clearable
                  :placeholder="t('login.pureUsername')"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  v-model="ruleForm.password"
                  clearable
                  show-password
                  :placeholder="t('login.purePassword')"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4 btn"
                color="#1774fa"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                {{ t("login.pureLogin") }}
              </el-button>
              <el-link
                class="mt-4"
                :underline="false"
                type="primary"
                @click="onForget"
              >
                {{ t("login.pureForgetPassword") }}?
              </el-link>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}

.login-form_wrap {
  :deep(.el-input--large) {
    --el-input-height: 56px;
  }

  :deep(.el-input__wrapper) {
    background: #f5f7fa;
    border-radius: 8px;
    box-shadow: none;

    .el-input__inner {
      font-size: 16px;
      font-weight: 400;
      color: #000c27;
    }

    .el-input__prefix-inner {
      .el-input__icon {
        justify-content: left;
        width: 45px;
        font-size: 24px;
        border-right: 1px solid #d7d8e0;
      }
    }
  }

  .btn {
    height: 56px;
    border-radius: 8px;
  }

  input:-internal-autofill-selected {
    background-color: transparent !important;
  }

  /* 针对 WebKit 浏览器（Chrome、Safari 等） */
  input:-webkit-autofill,
  textarea:-webkit-autofill,
  select:-webkit-autofill {
    box-shadow: 0 0 0 1000px white inset !important;
    -webkit-text-fill-color: var(--autata-font-color) !important;
  }

  /* 针对 Firefox */
  input.autofilled,
  textarea.autofilled,
  select.autofilled {
    box-shadow: 0 0 0 1000px white inset !important;
    -moz-text-fill-color: var(--autata-font-color) !important;
  }
}
</style>
